<script lang="ts" setup>
import { useVbenModal } from '@vben/common-ui';
import { message } from 'ant-design-vue';
import { useVbenForm } from '#/adapter/form';
import { useUserStore } from '#/store/user'

const userStore = useUserStore()

defineOptions({
  name: 'FormModelDemo',
});

const [Form, formApi] = useVbenForm({
  handleSubmit: onSubmit,
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'name',
      label: '姓名'
    },
    {
      component: 'InputNumber',
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'age',
      label: '年龄'
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'email',
      label: '邮箱'
    },
  ],
  showDefaultActions: false,
  wrapperClass: 'grid-cols-1',

});

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    await formApi.validateAndSubmitForm();
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const { values, isAdd } = modalApi.getData<{values: Record<string, any>, isAdd: boolean}>();
      // formApi.resetFields(); // 重置表单
      if (values) {
        formApi.setValues(values);
      }
      // 根据是添加还是编辑设置不同的标题
      // modalApi.setTitle(isAdd ? '添加用户' : '编辑用户');
    }
  },
  title: '内嵌表单示例',
});

function onSubmit(values: Record<string, any>) {
  message.loading({
    content: '正在提交中...',
    duration: 0,
    key: 'is-form-submitting',
  });
  modalApi.lock();
  
  const { isAdd } = modalApi.getData<{isAdd: boolean}>();
  console.log('isadd',isAdd)
  if (isAdd) {
    // 添加用户逻辑
    userStore.addUser(values);
  } else {
    // 编辑用户逻辑
    userStore.editUsers(values);
  }

  setTimeout(() => {
    modalApi.close();
    message.success({
      content: isAdd ? '添加用户成功' : '编辑用户成功',
      duration: 2,
      key: 'is-form-submitting',
    });
  }, 1000);
}
</script>

<template>
  <Modal>
    <Form />
  </Modal>
</template>
